﻿#include "WorkerThread.h"
#include <stdio.h>

int workerThreadInit(struct WorkerThread* thread, int index)
{
	thread->evLoop = NULL;
	thread->threadID = 0;
	sprintf(thread->name, "SubThread-%d", index);//命名线程
	pthread_mutex_init(&thread->mutex, NULL);//初始化互斥锁
	pthread_cond_init(&thread->cond, NULL);//初始化条件变量
	return 0;
}

// 子线程的回调函数
void* subThreadRunning(void* arg)
{
	struct WorkerThread* thread = (struct WorkerThread*)arg;//获取传入参数

	pthread_mutex_lock(&thread->mutex);//互斥锁上锁，与条件变量配合使用
	thread->evLoop = eventLoopInitEx(thread->name);//初始化eventloop
	pthread_mutex_unlock(&thread->mutex);

	pthread_cond_signal(&thread->cond);//evloop初始化完成，通知条件变量，释放互斥锁
	eventLoopRun(thread->evLoop);
	return NULL;
}
//启动线程
void workerThreadRun(struct WorkerThread* thread)
{
	// 创建子线程
	pthread_create(&thread->threadID, NULL, subThreadRunning, thread);//传入workThread结构体作为线程工作函数的参数
	// 阻塞主线程, 让当前函数不会直接结束，直到subThreadRunning 完成evloop初始化完成
	pthread_mutex_lock(&thread->mutex);
	while (thread->evLoop == NULL)//为空，evloop没有初始化
	{
		//必须与mutex 一起使用
		pthread_cond_wait(&thread->cond, &thread->mutex);//阻塞主线程，释放mutex，直到被唤醒重新上锁
	}
	pthread_mutex_unlock(&thread->mutex);
}